package com.weiz.service.Impl;

import com.weiz.domain.SysRole;
import com.weiz.domain.SysUser;
import com.weiz.dto.LoginUser;
import com.weiz.repository.SysRoleRepository;
import com.weiz.repository.SysUserRepository;
import com.weiz.service.UserService;
import com.weiz.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private SecurityUtils securityUtils;

    @Autowired
    private SysUserRepository sysUserRepository;

    @Autowired
    private SysRoleRepository sysRoleRepository;

    @Override
    public Boolean register(LoginUser loginUser) {
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String rawPassword = loginUser.getPassword();

        SysUser sysUser = new SysUser();
        sysUser.setUsername(loginUser.getUsername());
        sysUser.setPassword(encoder.encode(rawPassword));

        long roleId = loginUser.getLoginRole().getId();
        List<SysRole> roleList = new ArrayList<>();
        roleList.add(sysRoleRepository.findById(roleId).get());
        sysUser.setRoles(roleList);

        sysUserRepository.save(sysUser);
        return true;
    }


    @Override
    public Authentication authenticate(String username, String password) {
        return securityUtils.authenticate(username,password);
    }
}
